# -*- coding: utf-8 -*-

import re
import sys
from bs4 import BeautifulSoup
from chardet import detect

__author__ = 'Fonny'


def main():
	arg = sys.argv
	if arg.__len__() < 2:
		print(u'Error: 请通过参数传递要处理的文件'.encode('gbk'))
		return None

	# 处理传入的链接文件
	# for a in arg:
		# print(a)

	# return None

	# arg[0] 是py脚本的名称
	tarFile = arg[1]
	outFile = arg[2]
	# tarFile = '_out_\\index.html'
	try:
		f = open(tarFile).read()
	except Exception as err:
		print(u'Error: 打开文件失败'.encode('gbk') + err.message)
		print('Error: 打开文件失败')
		return None

	encoding = detect(f)['encoding']
	bso = BeautifulSoup(f, 'html5lib', from_encoding=encoding)

	aList = bso.select('#mainBody > p > a')

	# 写入外部文件
	try:
		# outf = open('_out_\\cmd_list.ini', 'w')
		outf = open(outFile, 'w')
		recop = re.compile(r'^http')

		for aItem in aList:
			# print(aItem.get_text())
			# print(aItem['href'])
			# cmdObj = {'name':aItem.get_text(), 'url':aItem['href']}
			# cmdList.append(cmdObj)
			if re.match(recop, aItem['href']):
				wstr = '[%s]\nurl=%s\n' % (str(aItem.get_text()).strip(' '), str(aItem['href']).strip(' '))
				outf.write(wstr)
	except Exception as err:
		print(u'Error: 写入文件失败'.encode('gbk') + err.message)
		# outf.close()
		exit(1)
	finally:
		outf.close()
	# print(os.path.abspath(outf))
	# re = json.dumps(repr(cmdList))
	# re = json.loads(repr(cmdList))
	# print(re)
	return None


if __name__ == '__main__':
	main()
